package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chixing.entity.Comment;
import com.chixing.entity.CommentImage;
import com.chixing.entity.Hotel;
import com.chixing.entity.Orders;
import com.chixing.mapper.CommentImageMapper;
import com.chixing.mapper.CommentMapper;
import com.chixing.mapper.HotelMapper;
import com.chixing.mapper.OrdersMapper;
import com.chixing.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chixing.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author smith
 * @since 2025-09-30
 */
@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CommentImageMapper commentImageMapper;
    @Autowired
    private HotelMapper hotelMapper;
    @Autowired
    private OrdersMapper ordersMapper;


    @Override
    public Result getCommentAll(Integer pageNum, Long userId ) {
        //  创建分页对象
        Page<Comment> page = new Page<>(pageNum,3);
        //  创建查询条件构造器
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        //  根据用户ID精确查询
        wrapper.eq("user_id",userId);
        //  执行分页查询,获取当前页码的评论数据
        Page<Comment> commentPage = commentMapper.selectPage(page,wrapper);
        //  从分页结果中获得评价记录列表
        List<Comment> commentList = commentPage.getRecords();
        List<Map<String, Object>> resultList = new ArrayList<>();  // 收集所有结果
        for (Comment comment : commentList) {
            Map<String,Object> map = new HashMap<>();
            //评价信息
            map.put("commentId",comment.getCommentId());
            map.put("comment",comment.getContent());
            map.put("rating",comment.getRating());
            map.put("createTime",comment.getCreateTime());
            map.put("replyContent",comment.getReplyContent());
            map.put("replyTime",comment.getReplyTime());
            //查询当前评论的图片
            QueryWrapper<CommentImage> imgWrapper = new QueryWrapper<>();
            imgWrapper.eq("comment_id",comment.getCommentId());
             List<CommentImage> imagesList = commentImageMapper.selectList(imgWrapper);
             List<String> imageUrls = new ArrayList<>();
             for (CommentImage img : imagesList) {
                 imageUrls.add(img.getImageAddress());
             }
             map.put("images",imageUrls);
            //酒店信息
            Hotel hotel = hotelMapper.selectById(comment.getHotelId());
            if(hotel!=null){
                map.put("hotelName",hotel.getHotelName());
                map.put("hotelImage",hotel.getHotelImage());
            }else {
                map.put("hotelName","酒店不存在");
                map.put("hotelImage","");
            }
            resultList.add(map);//将构建好的map添加到结果列表
        }
        // 返回分页信息
        Map<String, Object> response = new HashMap<>();
        response.put("list", resultList);
        response.put("total", commentPage.getTotal());
        response.put("pageNum", commentPage.getCurrent());
        response.put("pageSize", commentPage.getSize());
        response.put("totalPage", commentPage.getPages());
        return Result.getSuccess(response);
    }


    @Override
    @Transactional
    public Result saveComment(Comment comment) {
        comment.setCreateTime(LocalDateTime.now());
        // 保存评论
        int insertCount = commentMapper.insert(comment);
        if(insertCount<=0){
            return Result.saveFail("保存评论失败");
        }
        // 获取刚插入的评论ID
        Long commentId = comment.getCommentId();
        //获得订单ID
        Long orderId = comment.getOrderId();
        Orders order = new Orders();
        order.setOrderId(orderId);
        order.setIsComment(1);
        ordersMapper.updateById(order);
        //  保存图片
        if (comment.getImages() != null && !comment.getImages().isEmpty()) {
            for (int i = 0; i < comment.getImages().size(); i++) {
                String imgUrl = comment.getImages().get(i);
                CommentImage image = new CommentImage();
                image.setCommentId(commentId);
                image.setImageAddress(imgUrl);
                image.setUploadTime(LocalDateTime.now());
                image.setSort(i + 1);
                commentImageMapper.insert(image);
            }
        }

        //  返回结果
        return Result.saveSuccess("评论及图片保存成功");
    }

    @Override
    public Result getAllComments(Integer pageNum) {
        Page<Comment> page = new Page<>(pageNum,3);
        Page<Comment> commentPage = commentMapper.selectPage(page, null);
        if(commentPage!=null && commentPage.getTotal()>0)
            return Result.getSuccess(commentPage);
        return Result.getFail(null);
    }

    @Override
    @Transactional
    public Result deleteComment(Long userId,Long commentId) {
        QueryWrapper<CommentImage> imageWrapper = new QueryWrapper<>();
        imageWrapper.eq("comment_id",commentId);
        commentImageMapper.delete(imageWrapper);
        int rows = commentMapper.deleteById(commentId);
        if (rows > 0)
            return Result.deleteSuccess("删除成功");
        return Result.deleteFail("删除失败");
    }

}
